package main.java.com.yc.navy.snacknet.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yc.navy.snacknet.bean.TypeInfo;
import com.yc.navy.snacknet.enums.ResultEnum;
import com.yc.navy.snacknet.service.ITypeInfoService;
import com.yc.navy.snacknet.util.ConstantIfo;
import com.yc.navy.snacknet.vo.LayuiVO;
import com.yc.navy.snacknet.vo.ResultVO;

@RestController
@RequestMapping("/type")
public class TypeInfoCotroller {
	@Autowired
	private ITypeInfoService typeInfoService;
	
	/**
	 * 首页第一次分页查询
	 * @param map
	 * @return
	 */
	@PostMapping("/list")
	public LayuiVO list(@RequestParam Map<String, Object> map) {
		return typeInfoService.firstFind(map);
	}
	
	@GetMapping("/finds")
	public ResultVO finds() {
		List<TypeInfo> list = typeInfoService.finds();
		if(list != null && !list.isEmpty()) {
			return new ResultVO(ResultEnum.SUCCESS,list);
		}
		return new ResultVO(ResultEnum.DATA_NULL);
	}
	
//	@GetMapping("/findtname")
//	public ResultVO findtname() {
//		List<TypeInfo> list = typeInfoService.findtname();
//		if(list != null && !list.isEmpty()) {
//			return new ResultVO(ResultEnum.SUCCESS,list);
//		}
//		return new ResultVO(ResultEnum.DATA_NULL);
//	}
	
	
	@PostMapping("/add")
	public ResultVO add(TypeInfo tf, MultipartFile photo) {
		String savepath = "";
		File dest = null;
		
		if(photo != null && photo.getSize() > 0) {
			try {
				savepath = ConstantIfo.UPLOADPATH + "/" +System.currentTimeMillis() + "_" + photo.getOriginalFilename();
				dest = new File(ConstantIfo.SERVERPATH, savepath);
				//报存到指定文件
				photo.transferTo(dest);
				tf.setPic(savepath);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println(tf);
		int result = typeInfoService.add(tf);
		if(result > 0) {
			return new ResultVO(ResultEnum.SUCCESS);
		}
		
		if(result == -100) {
			return new ResultVO(ResultEnum.CHECK_ERROR);
		}	
		return new ResultVO(ResultEnum.ERROP);
	}
}
